---
title: Copy Button
description: Copy Button
layout: PreviewAndImplementation
---

## !demo

Add a copy button to a code block.

<Demo name="copy-button" />

## !implementation

First we make the button component:

```tsx button.tsx -c
"use client"

import { Copy, Check } from "lucide-react"
import { useState } from "react"

// !fold[/className="(.*?)"/gm]
export function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false)

  return (
    <button
      className="hover:bg-gray-400/20 p-1 rounded absolute top-1 right-1 text-zinc-200"
      aria-label="Copy to clipboard"
      onClick={() => {
        navigator.clipboard.writeText(text)
        setCopied(true)
        setTimeout(() => setCopied(false), 1200)
      }}
    >
      {copied ? <Check size={16} /> : <Copy size={16} />}
    </button>
  )
}
```

And then we use it when rendering the code block:

```tsx code.tsx -c
import { Pre, RawCode, highlight } from "codehike/code"
import { CopyButton } from "./button"

// !fold[/className="(.*?)"/gm]
async function Code({ codeblock }: { codeblock: RawCode }) {
  const highlighted = await highlight(codeblock, "github-dark")

  return (
    <div className="relative">
      <CopyButton text={highlighted.code} />
      <Pre className="m-0 px-4 bg-zinc-950" code={highlighted} />
    </div>
  )
}
```
